//
//  BaseController.m
//  StoneMason
//
//  Created by iOS1 on 16/12/5.
//  Copyright © 2016年 iOS1. All rights reserved.
//

#import "BaseViewController.h"
#import "MBProgressHUD.h"
#import "Login_VC.h"



@interface BaseViewController (){
    NSInteger seconds;
}
/**
 *  键盘出现移动的高度
 */
@property(nonatomic,assign)float movedHeight;
/**
 *  键盘动画是否出现 /防止多次的键盘动画
 */
@property (nonatomic,assign)BOOL isMoved;
/**
 *  键盘高度
 */
@property (nonatomic,assign)float keyboradY;

@property (nonatomic,assign)BOOL isShowLoadingWindow;

@property (nonatomic,strong) MBProgressHUD *loadingHUD;

@property (nonatomic, strong) UIView *msgView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIViewController *currentVc;

@property (nonatomic, strong) UICollectionView *currentCollectionVc;



@end

@implementation BaseViewController

-(instancetype)init {
    self = [super init];
    if (self) {
        _params = [[NSMutableDictionary alloc]init];
    }
    return self;
}

- (BOOL)isVisible {
    return (self.isViewLoaded && self.view.window);
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.alpha = 1;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = UIColorFromHex(0xeeeeee);
    [self initNavBackBtn];
    
    seconds = 0;
}

-(void)setSeparetInsert:(UITableViewCell *)cell distance:(NSInteger)distance{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, distance, 0,distance)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, distance, 0, distance)];
    }
}

#pragma mark - 外部方法
-(void)initNavBackBtn {
    NSArray *vcs = self.navigationController.viewControllers;
    if(vcs.count <= 2){
        if (vcs.count == 2) {
            if ([vcs[1] isKindOfClass:[Login_VC class]]) {
                self.navigationItem.hidesBackButton = YES;
                return;
            }
        }else{
            self.navigationItem.hidesBackButton = YES;
            return;
        }
    }
    if ([vcs[vcs.count-1] isKindOfClass:[Login_VC class]]){
        self.navigationItem.hidesBackButton = YES;
        return;
    }
    
    UIButton *leftBarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBarBtn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
    leftBarBtn.size = CGSizeMake(50, 44);
    leftBarBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    leftBarBtn.contentEdgeInsets = UIEdgeInsetsMake(-3, 0, 0, 0);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarBtn];
    [leftBarBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationController.navigationBar.translucent = NO;
    self.extendedLayoutIncludesOpaqueBars = YES;
}

-(void)initRightItem:(UIViewController *)curVc imgName:(NSString *)imgName title:(NSString *)title btnSize:(CGSize)size{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.size = size;
    if (imgName.length > 0) {
        [btn setImageEdgeInsets:UIEdgeInsetsMake(-3, 0, 0, -14)];
        [btn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    }
    [btn buttonWithTitle:title color:[UIColor whiteColor] font:FONT(16)];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [btn addTarget:self action:@selector(btnActionClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    curVc.navigationItem.rightBarButtonItem = rightItem;
}

-(void)btnActionClick{
    if (self.rightBarBtnItemBlock) {
        self.rightBarBtnItemBlock();
    }
}

-(void)setNavBackTinColor:(UIColor *)navBackTinColor{
    self.navigationController.navigationBar.tintColor = navBackTinColor;
}

-(void)backAction:(id)sender{
    [self popSelf];
}

-(void)delayPopViewController:(UIViewController *)vc{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [vc.navigationController popViewControllerAnimated:YES];
    });
}

-(void)pushViewController:(Class)class{
    BaseViewController *vc = [[class alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)popSelf {
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIView *)findFirstResponder:(UIView *)view {
    if (view.isFirstResponder) {
        return view;
    }
    for (UIView *subView in view.subviews) {
        UIView *firstResponder = [self findFirstResponder:subView];
        if (firstResponder != nil) {
            return firstResponder;
        }
    }
    return nil;
}

//获取view相对于屏幕的位置
- (CGRect)relativeFrameForScreenWithView:(UIView *)v {
    UIView *view = v;
    CGFloat x = .0;
    CGFloat y = .0;
    while (view.frame.size.width !=ScreenWidth|| view.frame.size.height != ScreenHight) {
        x += view.frame.origin.x;
        y += view.frame.origin.y;
        view = view.superview;
        if ([view isKindOfClass:[UIScrollView class]]) {
            x -= ((UIScrollView *) view).contentOffset.x;
            y -= ((UIScrollView *) view).contentOffset.y;
        }
    }
    return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
    //    CGPoint returnFrame = [v convertPoint:CGPointMake(v.frame.origin.x, v.frame.origin.y) toView:[UIApplication sharedApplication].keyWindow];
    //    CGRect frame = CGRectMake(returnFrame.x, returnFrame.y, v.width, v.height);
    //    return frame;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

-(void)showLoadingWindow:(NSString *)title {
    if (self.view.window == nil) return;
    [self.view endEditing:YES];
    self.loadingHUD = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    _loadingHUD.backgroundColor =  [UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:0.3];
    CGRect frame = self.view.window.frame;
    frame.origin.y += 64;
    frame.size.height -= 64;
    _loadingHUD.frame = frame;
    _loadingHUD.mode = MBProgressHUDModeIndeterminate;
    _loadingHUD.alpha = 0.8;
    if(title.length == 0){
        title = @"请稍等...";
    }
    _loadingHUD.label.text = title;
    self.isShowLoadingWindow = YES;
    if (ISIPHONE6) {
        _loadingHUD.label.font = [UIFont systemFontOfSize:14];
    }
    _loadingHUD.removeFromSuperViewOnHide = YES;
}

-(void)hideLoadingWindow {
    if (self.isShowLoadingWindow == YES) {
        [_loadingHUD hideAnimated:YES];
    }
    self.isShowLoadingWindow = NO;
}

-(void)showSimpleViewWithHead:(NSString *)titleStr message:(NSString *)content {
    if (content.length == 0 || !self.view.window) {
        return;
    }
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:titleStr message:content delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

-(BOOL)didLoginAction{
//    if (!isLogin()) {
//        Login_VC *loginVC = [[Login_VC alloc]init];
//        [self.navigationController pushViewController:loginVC animated:YES];
//        return NO;
//    }
    return YES;
}

-(id)pushViewController:(NSString *)className animated:(BOOL)animated params:(NSDictionary *)params {
    if (![self didLoginAction]) {
        return nil;
    }
    if (className == nil) {
        NSLog(@"传入类名为空");
    }
    Class clss = NSClassFromString(className);
    if ([clss isSubclassOfClass:[BaseViewController class]]) {
        BaseViewController *viewController = [[clss alloc]init];
        [viewController.params addEntriesFromDictionary:params];
        [viewController setValuesForKeysWithDictionary:params];
        [self.navigationController pushViewController:viewController animated:animated];
        return viewController;
    }else{
        NSLog(@"传入类名错误: %@",className);
    }
    return nil;
}



-(void)showNoDataMsg:(UIView *)v title:(NSString *)title{
    if (_msgView == nil) {
        CGFloat width = WIDTHINIPHONE6(100);
        self.msgView = [[UIView alloc] init];
        [v addSubview:_msgView];
        
        [_msgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(width+20));
            make.height.equalTo(@(width));
            make.centerX.centerY.equalTo(@0);
        }];
        
        UIImageView *imgView = [[UIImageView alloc] init];
        [imgView setImage:[UIImage imageNamed:@"no_data_msg"]];
        [_msgView addSubview:imgView];
        
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(@0);
            make.bottom.equalTo(@(-30));
        }];
        
        UILabel *msgLbl = [[UILabel alloc] init];
        if (title.length == 0) {
            title = @"未找到数据，联系客服!";
        }
        [msgLbl labelWithText:title color:UIColorFromHex(0x999999) font:FONT(15) textAlign:NSTextAlignmentCenter];
        msgLbl.numberOfLines = 0;
        [_msgView addSubview:msgLbl];
        
        [msgLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(width*2));
            make.height.equalTo(@15);
            make.centerX.equalTo(@0);
            make.bottom.equalTo(@0);
        }];
    }
}


#pragma mark -- 一键滑动到顶部
-(void)scrollTopAction{
    [_tableView setContentOffset:CGPointZero animated:NO];
}

-(void)durationShowView{
    if (seconds == 5) {
        seconds = 0;
        [_timer setFireDate:[NSDate distantFuture]];
        DefineWeakSelf;
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.topBtn.hidden = YES;
            weakSelf.homeBtn.hidden = YES;
        }];
    }
    seconds ++;
}

- (BOOL)stringContainsEmoji:(NSString *)string {
    if (string.length < 2) {
        return NO;
    }
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        const unichar hs = [substring characterAtIndex:0];
        // surrogate pair
        if (0xd800) {
            if (0xd800 <= hs && hs <= 0xdbff) {
                if (substring.length > 1) {
                    const unichar ls = [substring characterAtIndex:1];
                    const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                    if (0x1d000 <= uc && uc <= 0x1f77f) {
                        returnValue =YES;
                    }
                }
            }else if (substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                if (ls == 0x20e3) {
                    returnValue =YES;
                }
            }else {
                // non surrogate
                if (0x2100 <= hs && hs <= 0x27ff) {
                    returnValue =YES;
                }else if (0x2B05 <= hs && hs <= 0x2b07) {
                    returnValue =YES;
                }else if (0x2934 <= hs && hs <= 0x2935) {
                    returnValue =YES;
                }else if (0x3297 <= hs && hs <= 0x3299) {
                    returnValue =YES;
                }else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                    returnValue =YES;
                }
            }
        }
    }];
    return returnValue;
}

-(void)scrollTopShowNavBar:(UIScrollView *)scrollView scorllBlock:(isFinishedShowNavBarBlock)scrollBlock{
    int contentOffSetY = scrollView.contentOffset.y;
    self.navigationController.navigationBarHidden = NO;
    UINavigationBar *navBar = self.navigationController.navigationBar;
    CGFloat displacementY = HEIGTHINIPHONE6(248)-64;
    if (contentOffSetY < displacementY){
        navBar.alpha = scrollView.contentOffset.y / displacementY;
    }else {
        navBar.alpha = 1;
        return scrollBlock(YES);
    }
}

-(void)dialKeFu:(NSString *)tel{
    NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"yecht_kefu_alertView_msg_title", @""), tel];
    [ToolHelper showAlert:NSLocalizedString(@"yecht_kefu_alertView_title", @"") withMsg:msg cancelBtnTitle:NSLocalizedString(@"cancel", @"") okBtnTitle:NSLocalizedString(@"yecht_kefu_alertView_call_title", @"") withVc:self cancelBtnTitleColor:[UIColor colorWithHexString:@"999999"] confirmBlock:^{
        [ToolHelper dailContactPhoneWithNoPrompt:tel];
    }];
}

@end
